import { create } from 'zustand';
import { AppState, GameConfig, Character, TradeOffer, Notification, Player } from '../types';
import { gameManager } from '../game/GameManager';
import { propertyManager } from '../game/PropertyManager';
import { characterManager } from '../game/CharacterManager';
import { tradeManager } from '../game/TradeManager';

export const useGameStore = create<AppState>((set, get) => ({
  game: null,
  ui: {
    selectedPlayer: null,
    activeModal: null,
    notifications: [],
    isAnimating: false,
    diceResult: null,
    showPropertyCard: null,
    showEventCard: null,
    pendingChoice: null,
  },

  actions: {
    // 创建游戏
    createGame: (config: GameConfig) => {
      const gameId = `game-${Date.now()}`;
      set(state => ({
        game: {
          ...gameManager.initializeGame(config, []),
          id: gameId,
        },
      }));
    },

    // 加入游戏
    joinGame: (gameId: string, playerName: string, character: Character) => {
      const state = get();
      if (!state.game) return;

      const newPlayer: Player = {
        id: `player-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        name: playerName,
        character,
        position: 0,
        money: state.game.config.initialMoney,
        properties: [],
        items: [],
        isActive: true,
        isBankrupt: false,
        abilityLastUsed: 0,
        canReroll: character.id === 'lucky-charm',
      };

      set(state => ({
        game: state.game ? {
          ...state.game,
          players: [...state.game.players, newPlayer],
        } : null,
      }));
    },

    // 开始游戏
    startGame: () => {
      const state = get();
      if (!state.game) return;

      gameManager.startTurn(state.game);
      
      set(state => ({
        game: state.game ? {
          ...state.game,
        } : null,
      }));
    },

    // 掷骰子
    rollDice: () => {
      const state = get();
      if (!state.game) return;

      const diceResult = gameManager.rollDice();
      const currentPlayer = state.game.players[state.game.currentPlayerIndex];

      set(state => ({
        ui: {
          ...state.ui,
          diceResult,
          isAnimating: true,
        },
      }));

      // 移动玩家
      setTimeout(() => {
        const state = get();
        if (!state.game) return;

        gameManager.movePlayer(currentPlayer.id, diceResult, state.game);

        set(state => ({
          game: { ...state.game! },
          ui: {
            ...state.ui,
            isAnimating: false,
          },
        }));
      }, 1000);
    },

    // 结束回合
    endTurn: () => {
      const state = get();
      if (!state.game) return;

      gameManager.endTurn(state.game);

      set(state => ({
        game: { ...state.game! },
        ui: {
          ...state.ui,
          diceResult: null,
        },
      }));
    },

    // 购买地块
    buyProperty: (propertyId: string) => {
      const state = get();
      if (!state.game) return;

      const currentPlayer = state.game.players[state.game.currentPlayerIndex];

      try {
        propertyManager.buyProperty(currentPlayer.id, propertyId, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功购买地块！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '购买失败',
        });
      }
    },

    // 升级地块
    upgradeProperty: (propertyId: string) => {
      const state = get();
      if (!state.game) return;

      try {
        propertyManager.upgradeProperty(propertyId, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功升级地块！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '升级失败',
        });
      }
    },

    // 抵押地块
    mortgageProperty: (propertyId: string) => {
      const state = get();
      if (!state.game) return;

      try {
        propertyManager.mortgageProperty(propertyId, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功抵押地块！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '抵押失败',
        });
      }
    },

    // 赎回地块
    unmortgageProperty: (propertyId: string) => {
      const state = get();
      if (!state.game) return;

      try {
        propertyManager.unmortgageProperty(propertyId, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功赎回地块！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '赎回失败',
        });
      }
    },

    // 使用能力
    useAbility: (targetPlayerId?: string, targetPropertyId?: string) => {
      const state = get();
      if (!state.game) return;

      const currentPlayer = state.game.players[state.game.currentPlayerIndex];

      try {
        characterManager.useActiveAbility(
          currentPlayer.id,
          state.game,
          targetPlayerId,
          targetPropertyId
        );

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功使用能力！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '使用能力失败',
        });
      }
    },

    // 创建交易
    createTrade: (offer: Omit<TradeOffer, 'id' | 'status' | 'timestamp'>) => {
      const state = get();
      if (!state.game) return;

      try {
        tradeManager.createTradeOffer(
          offer.from,
          offer.to,
          offer.offering,
          offer.requesting,
          state.game
        );

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '交易提案已发送！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '创建交易失败',
        });
      }
    },

    // 响应交易
    respondToTrade: (tradeId: string, accept: boolean) => {
      const state = get();
      if (!state.game) return;

      try {
        if (accept) {
          tradeManager.acceptTrade(tradeId, state.game);
          get().actions.showNotification({
            type: 'success',
            message: '交易完成！',
          });
        } else {
          tradeManager.rejectTrade(tradeId, state.game);
          get().actions.showNotification({
            type: 'info',
            message: '交易已拒绝',
          });
        }

        set(state => ({
          game: { ...state.game! },
        }));
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '交易处理失败',
        });
      }
    },

    // 修改交易
    modifyTrade: (tradeId: string, changes: Partial<TradeOffer>) => {
      const state = get();
      if (!state.game) return;

      try {
        tradeManager.modifyTrade(tradeId, changes, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '交易已修改！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '修改交易失败',
        });
      }
    },

    // 出售地块
    sellProperty: (propertyId: string) => {
      const state = get();
      if (!state.game) return;

      try {
        propertyManager.sellProperty(propertyId, state.game);

        set(state => ({
          game: { ...state.game! },
        }));

        get().actions.showNotification({
          type: 'success',
          message: '成功出售地块！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: error instanceof Error ? error.message : '出售失败',
        });
      }
    },

    // 宣布破产
    declareBankruptcy: () => {
      const state = get();
      if (!state.game) return;

      const currentPlayer = state.game.players[state.game.currentPlayerIndex];
      currentPlayer.isBankrupt = true;

      set(state => ({
        game: { ...state.game! },
      }));

      get().actions.showNotification({
        type: 'warning',
        message: `${currentPlayer.name} 破产了！`,
      });

      get().actions.endTurn();
    },

    // 显示通知
    showNotification: (notification: Omit<Notification, 'id' | 'timestamp'>) => {
      const newNotification: Notification = {
        id: `notif-${Date.now()}`,
        timestamp: Date.now(),
        ...notification,
      };

      set(state => ({
        ui: {
          ...state.ui,
          notifications: [...state.ui.notifications, newNotification],
        },
      }));

      // 3秒后自动移除
      setTimeout(() => {
        get().actions.dismissNotification(newNotification.id);
      }, 3000);
    },

    // 移除通知
    dismissNotification: (notificationId: string) => {
      set(state => ({
        ui: {
          ...state.ui,
          notifications: state.ui.notifications.filter(n => n.id !== notificationId),
        },
      }));
    },

    // 设置活动模态框
    setActiveModal: (modalName: string | null) => {
      set(state => ({
        ui: {
          ...state.ui,
          activeModal: modalName,
        },
      }));
    },

    // 选择玩家
    selectPlayer: (playerId: string | null) => {
      set(state => ({
        ui: {
          ...state.ui,
          selectedPlayer: playerId,
        },
      }));
    },

    // 保存游戏
    saveGame: () => {
      const state = get();
      if (!state.game) return;

      try {
        localStorage.setItem('monopoly-saved-game', JSON.stringify(state.game));
        get().actions.showNotification({
          type: 'success',
          message: '游戏已保存！',
        });
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: '保存失败',
        });
      }
    },

    // 加载游戏
    loadGame: (gameId: string) => {
      try {
        const saved = localStorage.getItem('monopoly-saved-game');
        if (saved) {
          const game = JSON.parse(saved);
          set({ game });
          get().actions.showNotification({
            type: 'success',
            message: '游戏已加载！',
          });
        }
      } catch (error) {
        get().actions.showNotification({
          type: 'error',
          message: '加载失败',
        });
      }
    },

    // 清除保存的游戏
    clearSavedGame: () => {
      localStorage.removeItem('monopoly-saved-game');
    },
  },
}));
